import React from 'react';
import {Popover, Row, Modal, QueueAnim, Button, message} from 'antd';
import {WeaInput, WeaButton, WeaSelect, WeaInputSearch, WeaDatePicker, WeaBrowser, WeaTools, WeaFormItem, WeaLocaleProvider,
 WeaSearchGroup, WeaDialog } from 'ecCom';
import {WeaTableNew, WeaSwitch} from 'comsMobx';
import AboutTime from '../childComponents/aboutTime2';
import AboutBrowser from '../childComponents/aboutBrowser2';
import AboutSelsect from '../childComponents/aboutSelect2';
const getLabel = WeaLocaleProvider.getLabel;
const types = WeaTools.types;
const getKey = WeaTools.getKey;
import {inject, observer} from 'mobx-react';
import {toJS} from 'mobx';

const store = ['routing', 'weesoStore', 'weesoSeachSetStore']
@inject(...store)
@observer
export default class SearchTools extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    }
  }
  
  componentDidMount() {
    setTimeout(() => {
      const toolTip = $('.tool-icon-tip');
      if(toolTip){
        toolTip.fadeIn(300, () => {
          setTimeout(() => {
            toolTip.fadeOut(500);
          },1500)
        })
      }
    }, 3000);
    this.addStyle();
    document.addEventListener("click", this.maskFun,false);
  }

  componentWillUnmount() {
    const { setState } = this.props.weesoStore;
    setState({ showToolPopover: false });
    $('#esearch-propver-mask').remove();
    document.removeEventListener("click", this.maskFun,false);
    const { adSearchFormReset } = this.props.weesoSeachSetStore;
    adSearchFormReset();
  }

  maskFun = (e) => {
    const { setState } = this.props.weesoStore;
    if(e.target) {
      if(!$(e.target).hasClass('tool-right') && $(e.target).closest('.wesult-top-container').length > 0) {
        setState({ showToolPopover: false });
      }
      if($(e.target).hasClass('ant-popover-mask')) {
        setState({ showToolPopover: false });
      }
    }
  }

  addStyle = () => {
    const style = document.createElement('style');
    style.id = 'esearch-propver-mask';
    style.type = 'text/css';
    style.innerHTML = `.ant-popover-mask { 
      position: fixed;
      top: 115px;
      bottom: 0px;
      width: 100%;
    }`;
    document.getElementsByTagName('head')[0].appendChild(style);
  }

  adOnChange = () => {
    const { setState } = this.props.weesoSeachSetStore;
    setState({ searchTagParams: {} });
  }

  getSearchs() {
    const { adSearchForm, adSearchFormConditions } = this.props.weesoSeachSetStore;
    const { isFormInit } = adSearchForm;
    let group = [];
    isFormInit &&
      toJS(adSearchFormConditions).map((c, _index) => {
        let items = [];
        c.items.map(field => {
          let col = 1;
   
          items.push({
            com: (
              <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@crpx99@${field.domkey[0]}`}
                label={`${field.label}`}
                labelCol={{ span: `${field.labelcol}` }}
                ratio1to2
                error={adSearchForm.getError(field)}
                tipPosition="bottom"
                wrapperCol={{ span: `${field.fieldcol}` }}
              >
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@tz45a7@${field.domkey[0]}`}
                  fieldConfig={field}
                  form={adSearchForm}
                  onChange={this.adOnChange}
                />
              </WeaFormItem>
            ),
            col: col,
            hide: adSearchForm.isHide(field, (keys, allParams) => {
              return false;
            })
          });
        });
        group.push(
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@t6v5qa@${_index}`}
            needTigger={false}
            title={c.title}
            showGroup={c.defaultshow}
            items={items}
          />
        );
      });
    return group;
  }

  saveCommonCondition = () => {
    const { setState } = this.props.weesoSeachSetStore;
    const { inputValue } = this.props.weesoStore;
    setState({ commonDialogVisible: true, commonDialogInputVal: inputValue });
  }

  filterParams = () => {
    let { browserKeyArr, adSearchForm } = this.props.weesoSeachSetStore;
    const formParams = adSearchForm.getFormParams();
    let search_json = { ...formParams };
    delete search_json.showorder;
    delete search_json.tagName;
    delete search_json.tagTitle;
    browserKeyArr = toJS(browserKeyArr);
    Object.keys(search_json).forEach(key => {
      if(browserKeyArr.some(v => v === key)) {
        if(search_json[key] !== '') {
          search_json[key] = search_json[key].split(',');
        } else {
          delete search_json[key];
        }
      }
    });
    return search_json;
  }

  adSearchToolContent = () => {
    const {weesoStore} = this.props;
    let {searchDatas, showToolPopover, maskClosable, searchForm, getTypeDatas} = weesoStore;
    const { adSearchForm, searchTagParams, adSearchFormReset, setState } = this.props.weesoSeachSetStore;

    //高级搜索是否显示图标处理
    let searchParamsArray = [];
    const searchParams = adSearchForm.getFormParams();
    return(
      <div className="weeso-tool-popover" ref="contentWrapper">
        { this.getSearchs() }
        <div className="tool-btn">
          <WeaButton ecId={`${this && this.props && this.props.ecId || ''}_WeaButton@080v5e`} className="btn-left" type="primary" size="large"
            onClick={() => {
              if(searchParamsArray.length!==0) {
                weesoStore.isShowSearchIcon = true //控制是否显示图标
              }else {
                weesoStore.isShowSearchIcon = false
              }
              weesoStore.setState({
                showToolPopover: false,
                skipSearchParams: {
                  currentPage: 0,
                  lastRealNumber: 0,
                },
              });
              weesoStore.toolChangeInit();
              weesoStore.preSearch({
                searchTagId: searchTagParams.key || '',
                page_search_json: JSON.stringify(this.filterParams())
              });
            }}
            text={getLabel(197,"搜索")}
          />
           <WeaButton ecId={`${this && this.props && this.props.ecId || ''}_WeaButton@vzkvqd`} className="btn-left" type="primary" size="large"
            onClick={this.saveCommonCondition}
            text={getLabel('524258','存为常用条件') }
          />
          <WeaButton ecId={`${this && this.props && this.props.ecId || ''}_WeaButton@h6v2bu`} size="large"
            onClick={() => {
              setState({ searchTagParams: {} });
              adSearchFormReset();
            }}
            text={getLabel(2022,"重置")}
          />
        </div>
      </div>
    );
  }

  
  filterAdParams = (form, browserKeyArr) => {
    if(form === undefined || browserKeyArr === undefined) return; 
    const formParams = form.getFormParams();
    let search_json = { ...formParams };
    
    delete search_json.showorder;
    delete search_json.tagName;
    delete search_json.tagTitle;
    browserKeyArr = toJS(browserKeyArr);

    Object.keys(search_json).forEach(key => {
      let json = toJS(search_json[key]);
      if(typeof json === 'object') { // 过滤obj
        let objA = { ...search_json[key] };
        search_json = {
          ...search_json,
          ...objA
        };
      } 
      if(browserKeyArr.some(v => v === key)) {
        if(search_json[key] !== '') {
          search_json[key] = search_json[key].split(',');
        } else {
          delete search_json[key];
        }
      }

      browserKeyArr.forEach(v => {// 过滤浏览按钮span
        if(key.indexOf('span') > -1 && key.indexOf(v) > -1) {
          delete search_json[key];
        }
      });
 
      if(search_json[key] === '') {// 过滤''值
        delete search_json[key];
      }
    });
    if(search_json.CREATERID !== undefined && search_json.CREATERID !== '') {
      search_json = {
        ...search_json,
        CREATERID_select: '2'
      };
    }

    return search_json;
  }

  addCommonSaveBtn = () => {
    const { inputValue, defalutMoreKey } = this.props.weesoStore;
    let { setState, commonDialogInputVal, adSearchForm, browserKeyArr, doSaveSearchTag } = this.props.weesoSeachSetStore;
    const formParams = adSearchForm.getFormParams();
    if(commonDialogInputVal === '') {
      message.error(getLabel('524259','必填项未填写!') );
    } else {
      let search_json = this.filterAdParams(adSearchForm, browserKeyArr);

      let p = {
        id: '',
        search_type: defalutMoreKey,
        tagTitle: commonDialogInputVal,
        tagName: inputValue || commonDialogInputVal,
        search_json: JSON.stringify(search_json)
      };
      doSaveSearchTag(p, () => {
        setState({ commonDialogVisible: false, commonDialogInputVal: '' });
      });
    }
  }

  addCommonBtns = () => {
    let btns = [];
    btns.push(
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@s0i8mx@save`} type="primary" key={'save'} onClick={this.addCommonSaveBtn}>
        { getLabel('30986','保存') }
      </Button>,
    );
    return btns;
  }

  getDialog = () => {
    const dialogW = 600, dialogH = 140;
    const { collectParams, commonDialogVisible, setState, stepForm, stepConditions, commonDialogInputVal } = this.props.weesoSeachSetStore;
    return(<WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@jfe8da`} 
      className="weeso-search-add-common-conditions"
      visible={commonDialogVisible}
      title={getLabel('524258','存为常用条件') }
      icon={'icon-coms-ws'}
      iconBgcolor='#A0B0BA'
      style={{ width: dialogW, height: dialogH }}
      buttons={this.addCommonBtns()}
      onCancel={() => { setState({ commonDialogVisible: false }) }}
    >
      <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@4x6thl`}
        label={getLabel('23240','条件名称')}
        labelCol={{offset: 4, span: 4}}
        wrapperCol={{span: 12}}
      >
        <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@yhtdo4`} value={commonDialogInputVal} viewAttr={3} onChange={(val) => {setState({commonDialogInputVal: val});}}/>
        <div className="tip-message">{getLabel('524260','举例：一周内张三创建的文档') }</div>
      </WeaFormItem>
    </WeaDialog>);
  }

  adIconVisible = () => {
    let { searchTagParams } = this.props.weesoSeachSetStore;
    let { defalutMoreKey } = this.props.weesoStore;
    let bool = false;
    let formP = this.filterParams();
    if(searchTagParams.key && searchTagParams.key !== '') {
      bool = true;
    }
    if(formP) {
      Object.keys(formP).forEach(key => {
        if(key === 'CREATEDATE_date_select') {
        } else {
          if(typeof formP[key] === 'string') {
            formP[key] !== '' && (bool = true);
          }
          if(Array.isArray(formP[key]) && formP[key].length > 0) {
            bool = true;
          }
        }
      });
      if(formP.CREATEDATE_date_select  && formP.CREATEDATE_date_select !== '0') {
        bool = true;
      }
      if(defalutMoreKey === 'WKP') {
        if(formP.BEGINDATE_date_select === '0' && formP.CREATEDATE_date_select === '0') {
          bool = false;
          if(formP.RESOURCEID && formP.RESOURCEID.length > 0) {
            bool = true;
          }
        }
      }
    }
    if(defalutMoreKey === 'FAQ') {
      if(String(formP.updatedate_date_select) === '0') {
        bool = false;
      }
    }
    return bool;
  }

  render() {
    const {weesoStore} = this.props;
    let {searchDatas, showToolPopover, maskClosable, searchForm, getTypeDatas} = weesoStore;
    searchDatas = toJS(searchDatas);
    getTypeDatas = toJS(getTypeDatas);
    let key1 = searchDatas.key1 || '', pagese = searchDatas.pagese || '';
    const { getAdConditions, searchTagParams } = this.props.weesoSeachSetStore;
    //高级搜索是否显示图标处理
    let searchParamsArray = [];
    const searchParams = searchForm.getFormParams();
    for(let key in searchParams){
      let val = searchParams[key].toString();
      if(val !== '' && val !==','){
        searchParamsArray.push(val)
      }
    }

    const toolContent = (
      <div className="weeso-tool-popover" ref="contentWrapper">
        {this.getType()}
        <div className="tool-btn">
          <WeaButton ecId={`${this && this.props && this.props.ecId || ''}_WeaButton@1o5iat`} className="btn-left" type="primary" size="large"
            onClick={() => {
              if(searchParamsArray.length!==0) {
                weesoStore.isShowSearchIcon = true //控制是否显示图标
              }else {
                weesoStore.isShowSearchIcon = false
              }
            weesoStore.setState({
              showToolPopover: false,
              skipSearchParams: {
                currentPage: 0,
                lastRealNumber: 0,
              },
            });
              weesoStore.toolChangeInit();
              const { filterParams } = this.props.weesoSeachSetStore;
              let p = { page_search_json: JSON.stringify(filterParams())};
              weesoStore.preSearch(p);
            }}
            text={getLabel(197,"搜索")}
          />
           <WeaButton ecId={`${this && this.props && this.props.ecId || ''}_WeaButton@xyjtg6`} className="btn-left" type="primary" size="large"
            onClick={() => {
            }}
            text={getLabel('524258','存为常用条件') }
          />
          <WeaButton ecId={`${this && this.props && this.props.ecId || ''}_WeaButton@0p9lxk`} size="large"
            onClick={() => {
              weesoStore.resetForm();
            }}
            text={getLabel(2022,"重置")}
          />
        </div>
      </div>
    )
    let isChina = true;
    if(localStorage.languageidweaver === '8') {// 英文模式
      isChina = false;
    }

    return (
      <div className="result-tool">
        <p className="tool-left" style={{ width: isChina ? `calc(100% - 90px)` : `calc(100% - 160px)`  }} >
          <span className="tool-left-desc" title={key1&&key1.replace(/<\/?b.*?>/g, '')}>
            <span dangerouslySetInnerHTML={{__html: key1}}></span>
            {pagese}
          </span>
          {(key1 && weesoStore.showSubmitIcon) && 
          <span className="tool-icon">
            <i className='icon-coms-Service'
              onClick={() => weesoStore.doSubmit()}
              onMouseOver={() => $('.tool-icon-tip') && $('.tool-icon-tip').show()}
              onMouseOut={() => $('.tool-icon-tip') && $('.tool-icon-tip').hide()}
            />

            <div className='tool-icon-tip'>
              <p className="tool-tip-triangle"><span/></p>
              <p className="tool-tip-content">{getLabel(384972,'当前结果不满意？请点击这里')}</p>
            </div>

          </span>}
        </p>


        {this.getType().length != 0 &&
        <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@i2g6o7`} visible={showToolPopover} placement="bottom" content={this.adSearchToolContent()} trigger="click"
                //  onVisibleChange={(v) => {weesoStore.setState({showToolPopover: v})}}
                 mask={showToolPopover}
                 maskClosable={maskClosable}
                 zIndex={1000}
                 overlayClassName="weeso-style-popover weeso-ad-search-popver"
               
        >
          <p className={`tool-right ${this.adIconVisible() ? 'tool-right-show' : ''}`}
            onClick={() => {
              weesoStore.setState({showToolPopover: !showToolPopover}); 
              // getAdConditions({ id: searchTagParams.key||'', search_json: JSON.stringify(this.filterParams()) });
            }}
            style={{ width: isChina ? 90 : 160 }}
            >
            {getLabel(347,"高级搜索")}
            {this.adIconVisible() && <em className=" tool-right-icon icon-coms-screen2"></em>}
          </p>
        </Popover>
        }
        { this.getDialog() }
      </div>
    )
  }
  
  //处理搜索工具
  getSearchInfo = (type, item, bindObj) => {
    if (type == types.BROWSER) {
      return <AboutBrowser ecId={`${this && this.props && this.props.ecId || ''}_AboutBrowser@5e0ujb`} values={item} bindObj={bindObj}/>
    } else if (type == types.RANGEPICKER) {
      return <AboutTime ecId={`${this && this.props && this.props.ecId || ''}_AboutTime@mzuf37`} values={item} bindObj={bindObj}/>
    } else if (type == types.SELECT) {
      return <AboutSelsect ecId={`${this && this.props && this.props.ecId || ''}_AboutSelsect@p46jb7`} values={item} bindObj={bindObj} container={this.refs.contentWrapper}/>
    } else if (type == types.INPUT) {
      return (
        <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@86n046`}
          {...item}
          {...bindObj.bind()}
        />
      )
    }
  }
  
  getType = () => {
    const {weesoStore} = this.props;
    let {searchConditions, searchForm} = weesoStore;
    const {isFormInit} = searchForm;
    searchConditions = toJS(searchConditions);
    const arr = [];
    searchConditions && isFormInit && searchConditions.length!==0 && searchConditions.map(field => {
      const type = field.conditionType.toUpperCase();
      const key = getKey(field);
      const bindObj = searchForm.$(key);
      const searchParams = searchForm.getFormParams();
      if(type != types.RANGEPICKER || (key=='CREATEDATE_range_picker'&&type == types.RANGEPICKER && searchParams.CREATEDATE_date_select == '5')|| (key=='BEGINDATE_range_picker'&&type == types.RANGEPICKER && searchParams.BEGINDATE_date_select
        == '5')){
        arr.push(
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@7jfviq@${key}`}>
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@hafqbp@${key}`}
              label={`${field.label}`}
              labelCol={{span: `${field.labelcol}`}}
              wrapperCol={{span: `${field.fieldcol}`}}
              hideLabel = {type == types.RANGEPICKER}
            >
              {this.getSearchInfo(type, field, bindObj)}
            </WeaFormItem>
          </Row>)
      }
    })
    return arr;
  }
}
